package village.rainbow.slipin.util;

import java.io.IOException;

import village.rainbow.slipin.GpsService;
import village.rainbow.slipin.datamodel.DataRow;
import village.rainbow.slipin.datamodel.DataTable;
import android.app.Activity;
import android.media.ExifInterface;
import android.os.Build;

public class ExifUtil {
	
	public void saveGpsData(Activity activity, DataTable sceneDetailList) throws IOException {
		
		GpsService service = new GpsService(activity);
		
		if(service.canGetLocation()){
			for(DataRow row : sceneDetailList){
				String imgLocation = row.getString("SCENE_PIC_LOCATION", "");
				ExifInterface ef = new ExifInterface(imgLocation);
				
				ef.setAttribute(ExifInterface.TAG_MAKE, Build.MANUFACTURER);
				ef.setAttribute(ExifInterface.TAG_MODEL, Build.MODEL);
				
				ef.setAttribute(ExifInterface.TAG_GPS_LATITUDE, dec2DMS(service.getLatitude()));
				ef.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,dec2DMS(service.getLongitude()));
				if (service.getLatitude() > 0) 
					ef.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "N"); 
				else              
					ef.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "S");
				if (service.getLongitude()>0) 
					ef.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "E");    
				else             
					ef.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "W");
				
				ef.setAttribute(ExifInterface.TAG_GPS_DATESTAMP, StringUtil.currentDate("yyyy:MM:dd"));
				ef.setAttribute(ExifInterface.TAG_GPS_TIMESTAMP, StringUtil.currentDate("HH:mm:ss"));
				ef.setAttribute(ExifInterface.TAG_GPS_PROCESSING_METHOD, service.getGpsProcessMethod());
				
				ef.saveAttributes();
			}
		}
	}
	
	String dec2DMS(double coord) {  
		coord = coord > 0 ? coord : -coord;  // -105.9876543 -> 105.9876543
		String sOut = Integer.toString((int)coord) + "/1,";   // 105/1,
		coord = (coord % 1) * 60;         // .987654321 * 60 = 59.259258
		sOut = sOut + Integer.toString((int)coord) + "/1,";   // 105/1,59/1,
		coord = (coord % 1) * 60000;             // .259258 * 60000 = 15555
		sOut = sOut + Integer.toString((int)coord) + "/1000";   // 105/1,59/1,15555/1000
		return sOut;
	}

}
